<?
class Dispatcher {

    public $_uri = null;
    public $_uriSegments = null;

    protected function getActionName() {
        $action = "index";
        if(count($this->_uriSegments) > 1 && $this->_uriSegments[1]!="") $action = $this->_uriSegments[1];
        if($action{0}=="_") return false; // metodo inválido...
        if($action == "initController") return false;                
        return $action;
    }
   
    function __construct($router=null) {

        $uri = isset($_GET["r"]) ? $_GET["r"] : null;

        $default_controllerName = "home";

        if(!$router) $router = new Router(); // base default Router.
        $this->_uri = $router->route($uri);
        $this->_uriSegments = explode("/", trim($this->_uri,"/"));
        // el primer segmento de la uri es el nombre del controller
        $controllerName = trim($this->_uriSegments[0]);
        if($controllerName == "") $controllerName = $default_controllerName;        
        $actionName = $this->getActionName();
        if(!$actionName) $actionName = "index"; // default
        if(!$this->_dispatch($controllerName, $actionName)) die_not_found_page();

    }
    private function _dispatch($controllerName, $actionName) {

        $controller = Controller::factory($controllerName, $this->_uri);
        if(!$controller) return false;
                
        if(!$controller->isValidAction($actionName)) return false;// por seguridad, solo llamamos metodos existentes en la clase

        $args = array_slice($this->_uriSegments,2);
        call_user_func_array(array($controller, $actionName), $args);
        return true;
    }


}
?>
